﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using System.IO;

namespace SharedLib.WinFormMVCFramework.ExceptionHandling
{
    public class RecursiveExceptionFormatter : TextExceptionFormatter
    {
        public RecursiveExceptionFormatter(TextWriter writer, Exception exception, Guid handlingInstanceId)
            : base(writer, exception, handlingInstanceId)
        {
        }

        public override void Format()
        {
            Writer.WriteLine(GetExceptionContent(Exception));
            Writer.WriteLine("Exception Handling Instance ID: " + this.HandlingInstanceId);
        }

        private string GetExceptionContent(Exception ex)
        {
            if (ex == null) return null;
            StringWriter sw = new StringWriter();
            Exception tmp = ex;
            while (tmp != null)
            {
                sw.WriteLine(tmp.Message);
                sw.WriteLine(tmp.GetType().Name);
                sw.WriteLine(tmp.StackTrace);
                tmp = tmp.InnerException;
            }
            return sw.ToString();
        }
    }
}
